package com.maxmlr.music.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.maxmlr.music.admin.dao.RoleMapper;
import com.maxmlr.music.admin.dao.RoleMenuMapper;
import com.maxmlr.music.admin.entity.Role;
import com.maxmlr.music.admin.entity.RoleMenu;
import com.maxmlr.music.admin.param.RoleParam;
import com.maxmlr.music.admin.service.RoleService;
import com.maxmlr.music.admin.service.UserService;
import com.maxmlr.music.admin.service.transfer.RoleTransfer;
import com.maxmlr.music.common.base.BaseServiceImpl;
import com.maxmlr.music.common.exception.XmlrException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @author max
 * @version 1.0
 * @ClassName RoleServiceImpl
 * @Description 角色  服务实现类
 * @Copyright Copyright (c) 2020: www.maxmlr.com.
 * @since 2020-06-14
 */
@Slf4j
@Service
public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleTransfer roleTransfer;

    @Override
    @Transactional
    public boolean saveRole(RoleParam param) {
        Role role = roleTransfer.po2Role(param, userService.getAdminUser());
        save(role);
        List<RoleMenu> roleMenus = roleTransfer.po2RoleMenus(param.getMenuIds(), role.getId());
        roleMenus.forEach(p -> roleMenuMapper.insert(p));
        return true;
    }

    @Override
    @Transactional
    public boolean updateRole(RoleParam param) {
        Role role = getById(param.getId());
        if (Objects.isNull(role)) {
            throw new XmlrException("角色信息不存在");
        }
        roleTransfer.fullRole(role, param, userService.getAdminUser());
        updateById(role);
        List<RoleMenu> roleMenus = roleTransfer.po2RoleMenus(param.getMenuIds(), role.getId());
        roleMenuMapper.delete(Wrappers.<RoleMenu>lambdaQuery().eq(RoleMenu::getRoleId, role.getId()));
        roleMenus.forEach(p -> roleMenuMapper.insert(p));
        return true;
    }
}
